package us.codecraft.webmagic.samples;

import org.jsoup.nodes.Document;
import org.junit.jupiter.api.Test;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.samples.pipeline.MongodbPipeline;
import us.codecraft.xsoup.Xsoup;

import java.util.List;

public class SoqiPageProcessor  implements PageProcessor{

    public static final String URL_POST="http://www\\.soqi\\.cn/detail/id_(.+)\\.html";
    public static final String URL_LIST="http://www\\.soqi\\.cn/search\\.xhtml\\?keywords=(.*)&page=\\d+&city=\\d+&regCapital=\\d*&search_type=\\d+";

    private Site site=Site.me().setDomain("www.soqi.cn").setSleepTime(500).setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");


    @Override
    public void process(Page page) {
        //列表页
        if (page.getUrl().regex(URL_LIST).match()){
            List<String> links=page.getHtml().xpath("//nav[@class=\"page btm_page\"]").links().all();
            for(String str:links){
                if(str.matches(URL_LIST)){
                    page.addTargetRequest(str);
                }
            }
            List<String> pages=page.getHtml().xpath("//div[@class=\"list_lft_cont\"]").links().all();
            for(String str:pages){
                if(str.matches(URL_POST)){
                    page.addTargetRequest(str);
                }
            }
        }else {
            //文章页
            Document document=page.getHtml().getDocument();
            String companyName=Xsoup.compile("//div[@class=\"dn_more\"]/table/tbody/tr/td").evaluate(document).getElements().get(0).html();
            page.putField("companyName",companyName);
           // page.putField();
        }

    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new SoqiPageProcessor()).addPipeline(new MongodbPipeline()).addUrl("http://www.soqi.cn/search.xhtml?keywords=服装&page=2&city=100000&regCapital=4&search_type=1").run();
    }



    @Test
    public void testReg(){
        System.out.println("http://www.soqi.cn/detail/id_264A204YZIM4.html".matches(URL_POST));
        System.out.println("http://www.soqi.cn/search.xhtml?keywords=服装&page=2&city=100000&regCapital=&search_type=1".matches(URL_LIST));
    }

}
